package com.sibu.yx.promotion.admin.web.util;

import com.doubo.common.util.MD5Util;
import com.sibu.yx.promotion.persistence.model.sys.SysUser;
import lombok.Getter;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.util.ByteSource;

/**
 * Created with IntelliJ IDEA.
 * User: qiujingwang
 * Date: 2016/3/26
 * Description:密码加密
 */
public class PasswordHelper {
    private static PasswordHelper passwordHelper;

    public static PasswordHelper getInstance() {
        if (passwordHelper == null) {
            passwordHelper = new PasswordHelper();
        }
        return passwordHelper;
    }

    @Getter
    private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();

    private static int hashIterations = 2;


    public void encryptPassword(SysUser user) {
        user.setSalt(randomNumberGenerator.nextBytes().toHex());

        String newPassword = new Md5Hash(
                user.getPassword(),
                ByteSource.Util.bytes(user.getSalt()),
                hashIterations).toHex();

        user.setPassword(newPassword);
    }

    public String encryptPassword(String pwd, String salt) {
        return new Md5Hash(
                pwd,
                ByteSource.Util.bytes(salt),
                hashIterations).toHex();
    }

    public boolean matchPassword(SysUser user, String password) {
        return password != null && !password.isEmpty() && user != null && user.getPassword().equals(new Md5Hash(
                password,
                ByteSource.Util.bytes(user.getSalt()),
                hashIterations).toHex());
    }

    public boolean matchPassword(String userPassword, ByteSource userSalt, String password) {
        return password != null && !password.isEmpty() && userPassword != null && userPassword.equals(new Md5Hash(
                password,
                userSalt,
                hashIterations).toHex());
    }

    public static void main(String[] args) {
        SysUser sysUser = new SysUser();
        sysUser.setPassword(MD5Util.MD5("pcg!@0623"));
        PasswordHelper.getInstance().encryptPassword(sysUser);
        System.out.println(sysUser);
    }

}
